from utils.io.fileutils import getFilePath
from utils.config.propertiesFile import Properties
from utils.tool.stringPara import save_string, eval_string


# ===============================================================================
# ExtProperties
#     扩展的 Properties 文件访问，可以支持${xxxx} 变量形式
# ===============================================================================
class ExtProperties(Properties):

    def __init__(self, strFileName):
        self.filename = getFilePath(strFileName)
        super().__init__()
        with open(self.filename, 'r', encoding='UTF-8') as f:
            super().load(f)
        self.__savePara()

    # 保存properties中键值作为参数，{xxx}既可以使用
    def __savePara(self):
        # print(self.props.getPropertyDict())
        for key in self.propertyNames():
            value = self.getProperty(key)
            # print(key+'++'+value+'\n')
            save_string(value, key)

    def getProperty(self, key, defaultValue=''):

        def evalstr(sstr):
            return eval_string(eval_string(eval_string(sstr)))

        ret = evalstr(super().getProperty(key))
        return (ret if ret != "" else defaultValue)
        # else:
        #    return self.props.getProperty(key)

    '''* 返回如下的 default段
     * #####指定当前的 报文列表      #指定参数的默认值
        default=SWZJ.HXZG.SB.ZZSYBRSBSQJKJHQQCSJ,SWZJ.HXZG.SB.BCZZSXGMSB <br/>
        default.skssqq=2014-11-01 <br/>
        default.skssqz=2014-11-30 <br/>
        default.sbrq=2015-01-10 <br/>
     *
     * @return  
     * {skssqq=2014-11-01, <br/>
     * sbrq=2015-01-10, <br/>
     * skssqz=2014-11-30} <br/>
     * 
     * .=SWZJ.HXZG.SB.ZZSYBRSBSQJKJHQQCSJ,SWZJ.HXZG.SB.BCZZSXGMSB, '''
    def getSectionItems(self, sectionName):
        tmpData = {}
        for k in self.propertyNames():
            if k.startswith(sectionName):
                ss = k.replace(sectionName, '', 1)
                # 填入section默认值 .
                ss = ('.' if len(ss) == 0 else ss.replace('.', '', 1))
                # ss = k.split('.',1)
                tmpData[ss] = self.getProperty(k)
        return tmpData


def parsextProperties(file_name):
    return ExtProperties(file_name)


if __name__ == "__main__":
    sfile = "datas.conf"

    xp = ExtProperties(sfile)
    print(xp.getProperty("file.excel.folder"))
    print(xp)
    print(xp.getProperty("sdff", defaultValue="哈哈哈"))

    print(xp.getSectionItems("file.excel"))
    print(xp.getSectionItems("svn"))
